import {message, Space} from 'antd';
import React from 'react';
import MonacoEditor from 'react-monaco-editor';

interface Props {
    value: string;
    language?: string;
    height?: number;
    onChange?: (value: string) => void;
}

/**
 * 代码编辑器
 * @constructor
 */
const CodeEditor: React.FC<Props> = (props) => {
    const {value, height = 480, language = 'sql', onChange} = props;

    const options = {
        selectOnLineNumbers: true,
        fontSize: 14,
        formatOnPaste: true,
        automaticLayout: true,
        minimap: {
            enabled: false,
        },
    };

    const handleCopy = () => {
        navigator.clipboard.writeText(value).then(() => {
            message.success('复制成功!');
        }, () => {
            message.error('复制失败!');
        });
    };

    const handleDownload = () => {
        const blob = new Blob([value], {type: 'text/plain;charset=utf-8'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'code.' + new Date().getTime() + language;
        a.click();
        URL.revokeObjectURL(url);
    };

    return (
        <div>
            <div style={{
                display: 'flex',
                justifyContent: 'flex-end',
                textAlign: 'initial',
                padding: '4px 16px',
                background: '#1E1E1E',
                color: 'white',
            }}>
                <Space size={"large"}>
                    <a onClick={handleCopy}>复制</a>
                    <a onClick={handleDownload}>下载</a>
                </Space>
            </div>
            <MonacoEditor
                height={height}
                language={language}
                theme="vs-dark"
                value={value}
                options={options}
                onChange={onChange}
            />
        </div>
    );
};

export default CodeEditor;